package com.swordxu.yim.android.imlib.proto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.android.config.ProtocolConstant;
import com.swordxu.yim.android.imlib.network.packet.base.DefaultHeader;
import com.swordxu.yim.android.imlib.network.packet.base.Header;
import com.swordxu.yim.android.imlib.network.packet.base.Packet;
import com.swordxu.yim.android.log.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * MsgServerPacket:请求(返回)登陆消息服务器
 */

public class DepartmentPacket extends Packet {

	private Logger logger = Logger.getLogger(DepartmentPacket.class);

	public DepartmentPacket() {
		mRequest = new PacketRequest();
		setNeedMonitor(true);
	}

	@Override
	public String encode() {
		Header header = mRequest.getHeader();
		PacketRequest req = (PacketRequest) mRequest;
		if (null == req)
			return null;

        JSONObject jo = new JSONObject();
        jo.put("header", header);

        jo.put("body",  "");
        return jo.toJSONString();
	}

    @Override
    public void decode(String buffer) {
        if (null == buffer) {
            return;
        }

        PacketResponse res = new PacketResponse();

        JSONObject jo = JSON.parseObject(buffer);
        Header header = new Header();
        header = jo.getObject("header", Header.class);
        res.setHeader(header);
        JSONArray jsonArr = jo.getJSONArray("body");
        List<DepartmentEntity> list = new ArrayList<DepartmentEntity>();
        for (int i = 0; i < jsonArr.size(); i++) {
            DepartmentEntity entity = JSON.parseObject(jsonArr.get(i).toString(), DepartmentEntity.class);
            list.add(entity);
        }
        res.setEntityList(list);
        this.setmResponse(res);
    }

	public static class PacketRequest extends Request {
		public PacketRequest() {

			Header header = new DefaultHeader(ProtocolConstant.SID_BUDDY_LIST,
					ProtocolConstant.CID_BUDDY_LIST_DEPARTMENT_REQUEST);

//			int contentLength = 0;
//			header.setLength(SysConstant.PROTOCOL_HEADER_LENGTH + contentLength);

			setHeader(header);
		}
	}

	
	public static class PacketResponse extends Response {

        public List<DepartmentEntity> getEntityList() {
            return entityList;
        }

        public void setEntityList(List<DepartmentEntity> entityList) {
            this.entityList = entityList;
        }

        public List<DepartmentEntity> entityList = new ArrayList<DepartmentEntity>();
	}
}
